﻿using System.Collections.Generic;
using System.Diagnostics;

namespace JH
{
    /// <summary>
    ///  计时器池
    /// </summary>
    public static class StopWatchPool
    {
        /// <summary>
        ///   计时器池
        /// </summary>
        private static readonly Stack<Stopwatch> Pool = new();

        /// <summary>
        ///  获取一个计时器
        /// </summary>
        public static Stopwatch Get()
        {
            Stopwatch watch;
            lock (Pool)
            {
                watch = Pool.Count > 0 ? Pool.Pop() : new Stopwatch();
            }

            watch.Reset();
            return watch;
        }

        /// <summary>
        ///  释放计时器
        /// </summary>
        public static void Release(Stopwatch watch)
        {
            // 清空引用，避免内存泄漏
            watch.Reset();
            lock (Pool)
            {
                Pool.Push(watch);
            }
        }
    }
}